package com.zondy.mapgis.android.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.zondy.mapgis.android.utils.GPSUtil;
import com.zondy.mapgis.android.utils.StringUtils;
import com.zondy.mapgis.android.view.SatelliteView;
import com.zondy.mapgis.core.geometry.Dot;
import com.zondy.mapgis.explorer.R;

/**
 * 显示GPS详细信 fjl<br>
 * 暂时不支持蓝牙GPS信息
 */
public class GPSCenterActivity extends Activity
{

	private static final int MIN_UPDATE_TIME = 1000; // GPS最小更新时间 1s
	private static final float MIN_UPDATE_DISTANCE = 0; // GPS 最小更新距离 0

	private TextView mTile = null;
	private ImageView mTileBack = null; 

	private SatelliteView mSvSatellite;


	private TextView mTvLatitude;
	private TextView mTvLongitude;
	private TextView mTvHeight;
	private TextView mTvAccurate;
	private TextView mTvSpeed;
	private TextView mTvBear;
	private TextView mTvCoorX;
	private TextView mTvCoorY;
	private TextView mTvSateNum;

	private LocationManager mLocationManager;
	private boolean bOpened = false;

	private int mTimeCount;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_module_gpscenter);
		//透明状态栏  
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);  
        //透明导航栏  
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

		initCtrl();

		// 设置Timer
		final Handler handler = new Handler();
		Runnable runnable = new Runnable()
		{

			@Override
			public void run()
			{
				handler.postDelayed(this, 1000);
				mTimeCount++;
				if (mTimeCount == 1)
				{
					mSvSatellite.invalidate();
					mTvSateNum.invalidate();
					// GPS_Info.invalidate();
					mTimeCount = 0;
				}
			}
		};

		// 启动定时器
		handler.postDelayed(runnable, 1000);
		mTimeCount = 0;

	}

	@Override
	protected void onPause()
	{
		super.onPause();
		closeGpsListener();
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		openGpsListener();

	}

	/**
	 * 初始化各种控件
	 */
	private void initCtrl()
	{

		mTile = (TextView) findViewById(R.id.title_text);
		mTile.setText("星历图");
		mTileBack = (ImageView) findViewById(R.id.title_back);
		 

		mSvSatellite = (SatelliteView) findViewById(R.id.sv_gpscenter_satellite);

		mTvLatitude = (TextView) findViewById(R.id.tv_gpscenter_latitude);
		mTvLongitude = (TextView) findViewById(R.id.tv_gpscenter_longitude);
		mTvHeight = (TextView) findViewById(R.id.tv_gpscenter_height);
		mTvAccurate = (TextView) findViewById(R.id.tv_gpscenter_accurate);
		mTvSpeed = (TextView) findViewById(R.id.tv_gpscenter_speed);
		mTvBear = (TextView) findViewById(R.id.tv_gpscenter_bear);
		mTvCoorX = (TextView) findViewById(R.id.tv_gpscenter_coor_x);
		mTvCoorY = (TextView) findViewById(R.id.tv_gpscenter_coor_y);
		mTvSateNum = (TextView) findViewById(R.id.tv_gpscenter_sate_num);

		// add by hc 为用户提供一个良好的体验
		mTvLatitude.setText("未知");
		mTvLongitude.setText("未知");
		mTvHeight.setText("未知");
		mTvAccurate.setText("未知");
		mTvCoorX.setText("未知");
		mTvCoorY.setText("未知");
		mTvSpeed.setText("未知");
		mTvBear.setText("未知");

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


		mTileBack.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});

	}

	/**
	 * GPS定位监听
	 */
	private LocationListener locationListener = new LocationListener()
	{
		/**
		 * GPS状态变化时触发
		 */
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras)
		{
			mTvSateNum.setText(".....");
		}

		/**
		 * 位置信息变化时触发
		 */
		@Override
		public void onLocationChanged(Location location)
		{
			// 当GPS定位信息发生改变时，更新位置
			updateTextView(location);

		}

		/**
		 * GPS开启时触发
		 */
		@Override
		public void onProviderEnabled(String provider)
		{
			// 当GPS LocationProvider可用时，更新位置
			// 当尚未定位成功时，调用上次定位成功的坐标
			// updateView(locationManager.getLastKnownLocation(provider));

		}

		@Override
		public void onProviderDisabled(String provider)
		{
			updateTextView(null);

		}
	};

	/**
	 * GPS状态监听
	 */
	private GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener()
	{

		@Override
		public void onGpsStatusChanged(int event)
		{

			GpsStatus gpsStatus = mLocationManager.getGpsStatus(null);
			switch (event)
			{
			case GpsStatus.GPS_EVENT_FIRST_FIX:
				{

					// 第一次定位时间UTC gps可用
					@SuppressWarnings("unused")
					int i = gpsStatus.getTimeToFirstFix();
					break;
				}

			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
				{ // 周期的报告卫星状态
					// 得到所有收到的卫星的信息，包括
					// 卫星的高度角、方位角、信噪比、和伪随机号（及卫星编号）
					Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();

					List<GpsSatellite> satelliteList = new ArrayList<GpsSatellite>();

					for (GpsSatellite satellite : satellites)
					{
						// 包括 卫星的高度角、方位角、信噪比、和伪随机号（及卫星编号）
						/*
						 * satellite.getElevation(); //卫星仰角
						 * satellite.getAzimuth(); //卫星方位角 satellite.getSnr();
						 * //信噪比 satellite.getPrn(); //伪随机数，可以认为他就是卫星的编号
						 * satellite.hasAlmanac(); //卫星历书
						 * satellite.hasEphemeris(); satellite.usedInFix();
						 */
						satelliteList.add(satellite);
					}
					mSvSatellite.repaintSatellites(satelliteList);
					mTvSateNum.setText("" + satelliteList.size());
					break;
				}

			case GpsStatus.GPS_EVENT_STARTED:
				{
					break;
				}

			case GpsStatus.GPS_EVENT_STOPPED:
				{

					break;
				}

			default:

				break;
			}
		}
	};

	/**
	 * 更新myView上的显示内容
	 * 
	 * @param location
	 */
	public void updateTextView(Location location)
	{

		if (location != null && bOpened)
		{

			double longitudeDu = location.getLongitude();
			double latitudeDu = location.getLatitude();
			double altitude = location.getAltitude();
			double accuracy = location.getAccuracy();

			mTvLatitude.setText(GPSUtil.transDegreeTen2Ang(latitudeDu));
			mTvLongitude.setText(GPSUtil.transDegreeTen2Ang(longitudeDu));
			mTvHeight.setText(StringUtils.keepDecimal(altitude, 2));
			mTvAccurate.setText(String.valueOf(accuracy));
			mTvSpeed.setText(String.valueOf(location.getSpeed()));
			mTvBear.setText(String.valueOf(location.getBearing()));

			// PointD pntLand = getPosition(new PointD(longitudeDu,
			// latitudeDu));
			Dot pntLand = new Dot(10.0f, 12.0f);
			if (pntLand == null)
			{
				// 2015.07.21 modify by hc 让X坐标一直显示出来
				mTvCoorX.setText("未知");
			}
			else
			{
				mTvCoorX.setText(StringUtils.keepDecimal(pntLand.getX(), 2));
				mTvCoorY.setText(StringUtils.keepDecimal(pntLand.getY(), 2));
			}

		}
	}

	/**
	 * 获取大地坐标，使用当前地图的坐标系作为目标坐标系，根据配置确定是否使用七参数和偏移值。<br>
	 * 如果当前地图坐标系是WGS84，则返回null。
	 * 
	 * @param pntOrig
	 * @return
	 */
	// private PointD getPosition(PointD pntOrig){
	//
	// String strMapPath = SystemConfig.getConfig().getStrCurMapPath();
	// Map curMap = MapManager.getInstance().getMapByPath(strMapPath);
	//
	// Dot gpsdot = new Dot();
	// PointD pntResult = new PointD();
	//
	// if (null == pntOrig) {
	// return null;
	// }
	//
	// gpsdot.setX(pntOrig.getX());
	// gpsdot.setY(pntOrig.getY());
	//
	// SRefData srefMap = curMap.getSRSInfo();
	//
	// if (null == srefMap ) {
	// return null;
	// }
	//
	// SRefData srefWgs84 = SpaProjection.getWGS84Srs();
	//
	// int nSrsMapId = srefMap.getSRSID();
	// int nSrsWgsId = srefWgs84.getSRSID();
	// if(nSrsMapId == nSrsWgsId){
	// return null;
	// }
	//
	// Log.w("spaprojection_before", "x=" + gpsdot.x + " ,y=" + gpsdot.y);
	//
	// SpaProjection sp = new SpaProjection();
	// sp.setSourcePara(srefWgs84);
	// sp.setDestinationPara(srefMap);
	//
	// // 2013.8.16 by yangsheng. 使用七参数
	// boolean bUse7Para = SystemConfig.getConfig().isbUse7Para();
	//
	// double dPx = 0;
	// double dPy = 0;
	//
	// if (bUse7Para) {
	// sp.setEllipTransId((short) 0);
	// dPx = SystemConfig.getConfig().getdXpy();
	// dPy = SystemConfig.getConfig().getdYpy();
	// }
	//
	// sp.projTrans(gpsdot);
	//
	// Log.w("spaprojection_after", "x=" + gpsdot.x + " ,y=" + gpsdot.y);
	//
	// pntResult.setX(gpsdot.getX() + dPx);
	// pntResult.setY(gpsdot.getY() + dPy);
	//
	// return pntResult;
	// }

	/**
	 * 打开GPS定位监听器和状态监听器
	 */
	private void openGpsListener()
	{

		bOpened = true;
		// 从GPS获得最近的定位信息
		// Location
		// location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		// updateView(location);
		// 监听位置信息
		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, locationListener);
		// 监听GPS状态
		mLocationManager.addGpsStatusListener(gpsStatusListener);

		// //获取感应器服务
		// SensorManager sm=(SensorManager)
		// getSystemService(SENSOR_SERVICE);
		// //设置 随方向改变，compass旋转
		// sm.registerListener(mSensorListener,
		// SensorManager.SENSOR_MAGNETIC_FIELD,SensorManager.SENSOR_DELAY_UI);
	}

	/**
	 * 关闭监听器
	 */
	private void closeGpsListener()
	{
		bOpened = false;
		if (mLocationManager != null)
		{
			mLocationManager.removeGpsStatusListener(gpsStatusListener);
			mLocationManager.removeUpdates(locationListener);
		}
	}

	@Override
	public void onBackPressed()
	{
		finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
		super.onBackPressed();
	}

}
